<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<link href="${basePath}/js/upload/css/upload.css" rel="stylesheet">
<!doctype html>
<html>
<head>
	<style type="text/css">
		#container a{
			display: inline-block;
			line-height: 36px;
			height: 36px;
			padding-top: 0px;
		}
		
		.zhushi{
			color:#FC1515; 
			float: left; 
			line-height: 30px;
		}
		
	</style>
</head>
<body>
<div id="imgcontant" class="imgcontant" style="display: none;">
	<ul id="file-list"></ul>
	<div id="container">
		<label class="zhushi">注：双击图片下方标签可修改</label>
	    <a id="pickfiles" href="javascript:void(0);" class="btn dpbtn_blue">选择文件</a> 
	    <a id="uploadfiles" href="javascript:void(0);" class="btn dpbtn_green">开始上传</a>
	    <a id="destory" href="javascript:void(0);" class="btn dpbtn_red">结束上传</a>
	</div>
</div>

<!-- production -->
<script type="text/javascript" src="${basePath}/js/upload/js/plupload.full.min.js"></script>
<script type="text/javascript" src="${basePath}/js/upload/js/i18n/zh_CN.js"></script>
<!-- 文件上传 -->
<%@include file="/jsp/common_fileupload_include.jsp"%>

<script type="text/javascript">
	//跨域支持
	jQuery.support.cors=true;
	//登录页面
	var loginUrl = '${basePath}/web/login/login.jsp';
	var Qiniu_UploadUrl = "http://up.qiniu.com";
	//上传器
	var uploader;

	// modeId 模块
	var modeId;
	// ulId 展示图片ul标签ID
	var ulId;
	// customLabel 是否可自定义标签名称
	var customLabel;
	// isAdd 是否添加li来展示图片
	var isAdd;
	// fileLabelLi 标签码
	var fileLabelLi;
	// defaltLabelNameLi 默认标签名称
	var defaltLabelNameLi;
	// subId 子数据ID
	var subId;
	
	var img_json = {title : "img", extensions : img_extensions};
	var video_json = {title : "video", extensions : video_extensions};
	var word_json = {title : "word", extensions : word_extensions};
	var excel_json = {title : "excel", extensions : excel_extensions};
		
	/**
	 * obj 上传按钮
	 * types 文件类型 例如：img,word,excel,video 举例：img,word
	 */
     function uploadFileClicked(obj, types){
    	modeId = $(obj).attr('modeId');
 		ulId = $(obj).attr('ulId');
 		customLabel = $(obj).attr('customLabel') == 'true' ? true : false;
 		isAdd = $(obj).attr('isAdd') == 'true' ? true : false;
 		fileLabelLi = $(obj).attr('fileLabelLi');
 		defaltLabelNameLi = $(obj).attr('defaltLabelNameLi');
 		subId = $(obj).attr('subId');
 		var mimeTypes = new Array();
 		if(types && types != '') {
 			if(types.indexOf("img") >= 0) {
 				mimeTypes.push(img_json);
 			}
 			if(types.indexOf("video") >= 0) {
 				mimeTypes.push(video_json);
 			}
 			if(types.indexOf("word") >= 0) {
 				mimeTypes.push(word_json);
 			}
 			if(types.indexOf("excel") >= 0) {
 				mimeTypes.push(excel_json);
 			}
 		}
 		
 		if(mimeTypes.length == 0) {
 			mimeTypes.push(img_json);
 			mimeTypes.push(video_json);
 			mimeTypes.push(word_json);
 			mimeTypes.push(excel_json);
 		}
 		
		uploader = new plupload.Uploader({
			runtimes : 'html5,flash,silverlight,html4',
			browse_button : 'pickfiles', 
			container: 'container',
			url : Qiniu_UploadUrl,
			flash_swf_url : '${basePath}/js/upload/js/Moxie.swf',
			silverlight_xap_url : '${basePath}/js/upload/js/Moxie.xap',
			filters : {
				max_file_size : '2gb',
				mime_types: mimeTypes,
				prevent_duplicates : true //不允许选取重复文件
			},
			init: {
				PostInit: function() {
					$('#uploadfiles').unbind('click');
					$('#uploadfiles').click(function() {
						uploader.start();
						return false;
					});
					
					$('#destory').unbind('click');
					$('#destory').click(function() {
						uploader.destroy();
						$('#file-list').empty();
						layer.close(uploaderlayer);
						return false;
					});
				},
		
				FilesAdded: function(up, files) {
					for(var i = 0; i< files.length;  i++){
						var fileName = files[i].name; //文件名
						/* var file_size = files[i].size; 
						(' + plupload.formatSize(file_size) + ')//文件大小*/
						var fileType = parseAttachmentType(fileName);
						var html = '<li id="file-' + files[i].id +'"></li>';
						$(html).appendTo('#file-list');
						(function(i){
							previewImage(files[i],function(imgsrc){
								preImg(files[i], imgsrc);
							});
					    })(i);
					}
				},
				
				//上传文件前，预处理
				BeforeUpload:function(up,file){
					var fileName = file.name;
				    var extand = fileName.lastIndexOf(".");
				    var fileExt = fileName.substring(extand + 1, fileName.length);
				    var fileType = parseAttachmentType(fileName);
				    getTokenZ(fileExt, fileType, function(token, fileKey){
						callbackWithToken(token, fileKey);
						$('#file-'+file.id).find('.filename').attr('fileKey', fileKey);
					});
				},
		
				UploadProgress: function(up, file) {
					$('#file-'+file.id).children('b')[0].innerHTML = '<span class="uploadgreen">' + file.percent + "%</span>";
					$('#file-'+file.id).children('.changename').removeAttr("ondblclick");
				},
		
				Error: function(up, err) {
					var file = err.file;
					if(file){
						var $b = $('#file-'+file.id).children('b');
						if($b && $b.length > 0) {
							$b[0].innerHTML = '<span class="uploadstatok uploadgred">' + err.message + '</span>';
						} else {
							layer.msg(err.message, {icon:7});
						}
					}
				},
				
				//上传成功后执行
				FileUploaded:function(uploader,file,responseObject){
					var holdSpan = $('#file-'+file.id).find('.filename');
					var currentCustomLabelName = holdSpan.text().trim();
					var currentFileName = holdSpan.attr('fileName');
					var currentFileKey = holdSpan.attr('fileKey');
					getUrl(ulId, file, currentFileName, modeId, currentCustomLabelName, customLabel, isAdd, fileLabelLi, defaltLabelNameLi, subId, null, null, true, currentFileKey,function(){
						$('#file-'+file.id).children('b')[0].innerHTML = '<span class="uploadstatok uploadgreen">上传成功</span>';
						$('#file-'+file.id).children('div.imgnone').remove();
						$('#file-'+file.id).children('.changename').removeAttr("ondblclick");
					});
					
				}
			}
		});
 		uploader.init();
 		
 		uploaderlayer=layer.open({
		    	  type: 1,
		    	  title:'文件上传-' + defaltLabelNameLi,
		    	  shadeClose: true,
		    	  shade: 0.8,
		    	  area: ['60%', '410px'],
		    	  content: $('#imgcontant'),
		    	  end: function(){
		    		  uploader.destroy();
					  $('#file-list').empty();
					  layer.close(uploaderlayer);
		    	}
	    });
     }
	
     var uploaderlayer;
     
	//plupload中为我们提供了mOxie对象,预览图片
	function previewImage(file,callback){//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
		if(!file) return; 
		var fileName = file.name;
	    if(parseAttachmentType(fileName) == '${attachmentTypeNames.IMAGE}') {
		    //确保文件是图片
			if(file.type=='image/gif'){//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
				var fr = new mOxie.FileReader();
				fr.onload = function(){
					callback(fr.result);
					if(fr != null) {
						fr.destroy();
						fr = null;
					}
				}
				fr.readAsDataURL(file.getSource());
			}else{
				var preloader = new mOxie.Image();
				preloader.onload = function() {
					preloader.downsize( 110, 110 );//先压缩一下要预览的图片,宽110，高110
					var imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
					callback && callback(imgsrc); //callback传入的参数为预览图片的url
					if(preloader != null) {
						preloader.destroy();
						preloader = null;
					}
				};
				preloader.load(file.getSource() );
			}	
	    } else if(parseAttachmentType(fileName) == '${attachmentTypeNames.WORD}'){
	    	preImg(file, otherimg);
	    }  else if(parseAttachmentType(fileName) == '${attachmentTypeNames.EXCEL}'){
	    	preImg(file, otherimg);
	    }  else if(parseAttachmentType(fileName) == '${attachmentTypeNames.VIDEO}'){
	    	preImg(file, otherimg);
	    }
	}
	
	function preImg(file, defaultImgUpload){
		var content = '<img src="'+ defaultImgUpload +'" />'
			 +'<div class="imgnone"><div class="deleteico" data-val=' + file.id +'></div>'
			    +'<span onclick="deleteico(\'' + file.id +'\');" class="imgattr">'
				+'<img src="${basePath}/js/upload/img/delete.png" alt="删除" title="删除" /></span>'
		    +'</div>'
		    +'<div class="lablename"></div>'
		    +'<div class="changename" ondblclick="editor(this,\'' + file.name + '\')"><span class="filename" fileName= "' + file.name + '">' + defaltLabelNameLi + '</span></div><b></b>';
			
		$('#file-'+file.id).html(content);
		//鼠标移入出现
		$('#file-'+file.id).mouseover(function(){
			$(this).find(".imgnone").show();
			/* var $fileNameSpan = $(this).find(".filename");
			var $fileNameInput = $(this).find(".inputclass");
			
			var text;
			var $obj;
			var time;
			if($fileNameSpan && $fileNameSpan.length > 0) {
				text = "双击修改标签";
				$obj = $fileNameSpan;
				time = 2000;
			} else {
				text = "输入标签";
				$obj = $fileNameInput;
				time = 1000;
			}
			if($obj && $obj.length > 0) {
				layer.tips(text, $obj,{
					 tips: [1, '#3595CC'],
					 time:time
				});
			} */
		});
		//鼠标移出隐藏
		$('#file-'+file.id).mouseout(function(){
			$(this).find(".imgnone").hide();
		});
	}
	
	//预览中删除图片
	function deleteico(id){
		if(!id || id == '') {
			return;
		}
		var thisFile = uploader.getFile(id);
		$('#file-' + id).remove();
		if(thisFile) {
			uploader.removeFile(thisFile);
		}
	}
	//自定义标签双击修改
	function editor(th,fileName){
		 $span = $(th).find(".filename");
		 var preLabel = $span.text().trim();
		 $span.remove();
		 $(th).html('<input class="inputclass" type="text" placeholder="输入标签" maxLength="6" onblur="upperCase(this,\'' + preLabel + '\',\'' + fileName + '\');"/>');
		 $(th).find(".inputclass").focus(); 
	} 
	
	function upperCase(obj, preLabel, fileName){
		var value = obj.value;
		var $div = $(obj).parents(".changename");
		if(!value || value.trim() == ""){
			$div.html('<span class="filename" fileName= "' + fileName + '">'+preLabel+'</span>');
		} else {
		   $div.html('<span class="filename" fileName= "' + fileName + '">'+value+'</span>');
		}
		$(obj).remove();
	}
	
	//获取token
	function getTokenZ(fileExt, fileType, callback) {
		fileExt = fileExt || 'png';
		$.dpAjax({
			async:false,
			show:false,
			data : {fileType : fileExt, type:fileType},
			url : '${basePath}/QiniuFileController/getToken',
			success : function(data) {
				var result = data.result;
				var token = result.token;
				var fileKey = result.uuid;
				callback(token, fileKey);
			},
			error : function(a, statusText, c) {
				if (statusText && statusText != '') {
					layer.msg(statusText, {icon : 2});
				}
			}
		});
	}
	//使用token上传
	function callbackWithToken(token, fileKey) {
		var file = {
			token : token,
			key : fileKey
		}
		uploader.setOption({
			'multipart_params' : file
		});
	}
</script>
</body>
</html>
